package com.bee.health;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bee.health.util.AChartEngineUtil;
import com.juma.sdk.JumaDevice;
import com.juma.sdk.JumaDeviceCallback;
import com.juma.sdk.ScanHelper;
import com.juma.sdk.ScanHelper.ScanCallback;
/**
 * 思路：1.从布局中设置data的测试数据
 *   正式：2.从下面获取数据为y，（同时）存储起来（日期，值）；3.在初始化的时候把存储的值读上来
 * @author bee
 *
 */
public class StepCountActivity extends Activity {
	private TextView tv_bs_count;
	private TextView tv_bs_kll;
	private LinearLayout ll_bar;
	
	DecimalFormat df = new DecimalFormat("#.##");
	private ScanHelper scanner;//扫描设备类
	private JumaDevice myDevice;//设备
	
	List<String> data = new ArrayList<String>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_step_count);
		ll_bar = (LinearLayout) findViewById(R.id.ll_bar);//得到资源
		tv_bs_count = (TextView) findViewById(R.id.tv_bs_count);
		tv_bs_kll = (TextView) findViewById(R.id.tv_bs_kll);
		
		data.add("4025");
		data.add("8004");
		data.add("4631");
		data.add("10252");
		data.add("4569");
		data.add("6515");
		data.add("14360");
		
		
		scanDevice();
		scanner.startScan(null);//扫描周围所有的设备
		AChartEngineUtil.setchart(StepCountActivity.this,ll_bar,new String[]{"步数"},new int[]{Color.GREEN},data,"时间","步数");
		//initView();//初始化柱状图
	}
	
	/**
	 * 搜索设备
	 * 这个是当检测到蓝牙的时的回调函数
	 */
	private void scanDevice() 
	{
		scanner = new ScanHelper(getApplicationContext(), new ScanCallback() {
			
			@Override
			public void onScanStateChange(int arg0)
			{
				
			}
			
			@Override
			public void onDiscover(JumaDevice device, int rssi)
			{
				if("NigeL".equals(device.getName())){
                    myDevice = device;
                    myDevice.connect(callback);
                    Toast.makeText(getApplicationContext(), "蓝牙配对成功", 1).show();
				}
			}
		});
	}
	
	/**
	 * 该类用于获取与BLE设备通信相关的事件，如接收到数据、断开连接、发送数据等，以Callback的方式通知应用程序：
	 */
	private JumaDeviceCallback callback =new JumaDeviceCallback() {

		@Override
		public void onConnectionStateChange(int status, int newState) {
			// TODO Auto-generated method stub
			super.onConnectionStateChange(status, newState);
			if(newState == JumaDevice.STATE_CONNECTED && status == JumaDevice.SUCCESS){
				System.out.println("设备连接成功");
			}
		}

		private short bx = 0,by = 0,bz = 0,step=12500;
	
		@Override
		public void onReceive(byte type, byte[] message) {//我修改了final
			super.onReceive(type, message);
		
			//System.out.println("数据！！！！！！！！");
			bx = 0;
			by = 0;
			bz = 0;
			step=0;
			bx |= message[0];
			bx <<= 8;
			bx |= (message[1]&0x00FF);
			by |= message[2];
			by <<= 8;
			by |= (message[3]&0x00FF);
			bz |= message[4];
			bz <<= 8;
			bz |= (message[5]&0x00FF);
			step |= message[6];
			step <<= 8;
			step |= (message[7]&0x00FF);
			
		    System.out.println(step+"");
	
			
			runOnUiThread(new Runnable() 
			{
				
				@Override
				public void run() 
				{
					
					tv_bs_count.setText(step+12500+"");
					tv_bs_kll.setText(df.format(Kcal(step))+"Kcal");
				}
			});
			
		}

		/**
		 * 卡路里
		 * @param list2
		 * @return
		 */
		private float Kcal(int step)
		{
			return (float) (70*((step*0.6+12500*0.6)/1000)*1.036);
		}
		
		
		
		@Override
		public void onRemoteRssi(int status, int rssi) {
			// TODO Auto-generated method stub
			super.onRemoteRssi(status, rssi);
		}

		@Override
		public void onSend(int status) {
			// TODO Auto-generated method stub
			super.onSend(status);
		}

		@Override
		public void onUpdateFirmware(int status) {
			// TODO Auto-generated method stub
			super.onUpdateFirmware(status);
		}
		
	};
	
	
	
    /**
     * 如果恢复界面，就再次链接
     */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(null!=myDevice){
			myDevice.connect(callback);
		}
		
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if(myDevice != null && myDevice.isConnected())
			myDevice.disconnect();
		
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(myDevice != null && myDevice.isConnected())
			myDevice.disconnect();
	}
	
	/**
	 * 初始化柱状图
	 *//*
	private void initView() 
	{
		String[] titles = new String[] { "步数" };//柱状图列个序列的名字
		ArrayList<double[]> value = new ArrayList<double[]>();//存放柱状图两个序列
		double[] d1 = new double[] { 0.1, 0.3, 0.7, 0.8, 0.5 };//柱子上面的值!!!!!!!!也就是把这些值放进去就有数据
		value.add(d1);
		int [] colors = {Color.GREEN};//柱状图的颜色
		ll_bar.addView(
				xychar(titles, value, colors, 6, 1, new double[] { 2007,
						2012.5, 0, 1 }, new int[] { 2008, 2009, 2010, 2011,
						2012 }, "步数表", true),
				new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT));
		
	}
	*//**
	 * 
	 * @param titles //两个主的标题
	 * @param value //柱子的值
	 * @param colors//柱子的颜色
	 * @param x //设置x轴标签数
	 * @param y
	 * @param range 设置x轴和y轴的最大最小值！！！！！
	 * @param xLable X坐标值
	 * @param xtitle  表的标题
	 * @param f
	 * @return
	 *//*
	public GraphicalView xychar(String[] titles, ArrayList<double[]> value,
			int[] colors, int x, int y,double[] range, int []xLable ,String xtitle, boolean f) {
		//多个渲染
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		//多个序列的数据集
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		//构建数据集以及渲染
		for (int i = 0; i < titles.length; i++) 
		{
		
			XYSeries series = new XYSeries(titles[i]);
			double [] yLable= value.get(i);
			for (int j=0;j<yLable.length;j++)
			{
				series.add(xLable[j],yLable[j]);
			}
			dataset.addSeries(series);
			XYSeriesRenderer xyRenderer = new XYSeriesRenderer();
			// 设置颜色
			xyRenderer.setColor(colors[i]);
			// 设置点的样式 //
			xyRenderer.setPointStyle(PointStyle.SQUARE);
			// 将要绘制的点添加到坐标绘制中

			renderer.addSeriesRenderer(xyRenderer);
		}
		//设置x轴标签数
		renderer.setXLabels(x);
		//设置Y轴标签数
		renderer.setYLabels(y);
		//设置x轴的最大值
		renderer.setXAxisMax(x - 0.5);
		//设置轴的颜色
		renderer.setAxesColor(Color.BLACK);
		//设置x轴和y轴的标签对齐方式
		renderer.setXLabelsAlign(Align.CENTER);
		renderer.setYLabelsAlign(Align.RIGHT);
		// 设置现实网格
		renderer.setShowGrid(true); 
	
		renderer.setShowAxes(true); 
		// 设置条形图之间的距离
		renderer.setBarSpacing(0.2);
		renderer.setInScroll(false);
		renderer.setPanEnabled(false, false);
		renderer.setClickEnabled(false);
		//设置x轴和y轴标签的颜色
		renderer.setXLabelsColor(Color.RED);
		renderer.setYLabelsColor(0,Color.RED);
      
		int length = renderer.getSeriesRendererCount();
		//设置图标的标题

		renderer.setChartTitle(xtitle);
		renderer.setLabelsColor(Color.RED);

		//设置图例的字体大小
		renderer.setLegendTextSize(18);
		//设置x轴和y轴的最大最小值
		renderer.setRange(range);
		renderer.setMarginsColor(0x00888888);
		for (int i = 0; i < length; i++) {
			SimpleSeriesRenderer ssr = renderer.getSeriesRendererAt(i);
			ssr.setChartValuesTextAlign(Align.RIGHT);
			ssr.setChartValuesTextSize(12);
			ssr.setDisplayChartValues(f);
		}
		GraphicalView mChartView = ChartFactory.getBarChartView(getApplicationContext(),
				dataset, renderer, Type.DEFAULT);
		return mChartView;

	}*/

}
